package com.tbabs.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tbabs.common.BaseContext;
import com.tbabs.common.R;
import com.tbabs.entity.ShoppingCart;
import com.tbabs.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @PostMapping("/{as}")
    public R<ShoppingCart> addOrSub(@PathVariable String as, @RequestBody ShoppingCart shoppingCart){
        // 设置用户id
        Long userId = BaseContext.getCurrentId();
        shoppingCart.setUserId(userId);

        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        // 判断当前菜品或套餐是否在购物车中
        if (shoppingCart.getDishId() != null) {
            // 当前添加的是菜品
            queryWrapper.eq(ShoppingCart::getDishId, shoppingCart.getDishId())
                    .eq(ShoppingCart::getUserId, userId);
        }else{
            // 当前添加的是套餐
            queryWrapper.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId())
                    .eq(ShoppingCart::getUserId, userId);
        }
        ShoppingCart cart = shoppingCartService.getOne(queryWrapper);
        if (cart != null) {
            // 如果已经存在，则加一
            Integer number = cart.getNumber();
            if ("add".equals(as)) {
                cart.setNumber(number + 1);
            }else{
                if (number == 1) {
                    shoppingCartService.remove(queryWrapper);
                }else{
                    cart.setNumber(number - 1);
                }
            }
            shoppingCartService.updateById(cart);
        }else {
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartService.save(shoppingCart);
            cart = shoppingCart;
        }

        return R.success(cart);
    }

    @GetMapping("/list")
    public R<List<ShoppingCart>> list(){
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId())
                .orderByAsc(ShoppingCart::getCreateTime);

        List<ShoppingCart> list = shoppingCartService.list(queryWrapper);

        return R.success(list);
    }

    @DeleteMapping("/clean")
    public R<String> clean(){
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());

        shoppingCartService.remove(queryWrapper);

        return R.success("清除购物车成功！");
    }
}
